<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="商品查询">
        <el-input v-model="bindForm.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select v-model="bindForm.status" placeholder="分类状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="add('form')">新建</el-button>

      </el-form-item>
    </el-form>
    <!-- 新建/修改商品 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="商品名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分类图片" :label-width="formLabelWidth" prop="img">
          <upload-img v-model="form.img" @getUrl="getCover" />
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" autocomplete="off" type="number" :min="0" @input="valueInput">></el-input>
        </el-form-item>
        <el-form-item label="商品库存" :label-width="formLabelWidth" prop="stock">
          <el-input v-model="form.stock" autocomplete="off" type="number" />
        </el-form-item>
        <el-form-item label="商品分类" :label-width="formLabelWidth" prop="category">
          <el-select v-model="form.category" placeholder="请选择商品分类">
            <el-option
              v-for="item in categoryList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格" :label-width="formLabelWidth" prop="sku">
          <el-table
            :data="form.sku"
            border
            style="width: 100%"
          >
            <el-table-column
              label="规格名称"
              width="180"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.skuName" />
              </template>
            </el-table-column>
            <el-table-column
              label="规格内容"
              width="240"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.skuContent" />
              </template>
            </el-table-column>
            <el-table-column
              label="规格价格"
              width="120"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.skuPrice" />
              </template>
            </el-table-column>
            <el-table-column
              label="规格库存"
              width="120"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.skuStock" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="addSku"
                >新增</el-button>
                <el-button
                  v-if="form.sku.length>1"
                  size="mini"
                  type="danger"
                  @click="delSku(scope)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <quill-editor-vue :contents="form.details" ref-value="deatilsRef" :index="0" @getSon="quillDetail" />
        </el-form-item>
        <el-form-item label="套餐内容" :label-width="formLabelWidth">
          <quill-editor-vue :contents="form.mealContont" ref-value="mealContontRef" :index="1" @getSon="quillMeal" />
        </el-form-item>
        <el-form-item label="购买须知" :label-width="formLabelWidth">
          <quill-editor-vue :contents="form.purchaseNotes" ref-value="purchaseNotesRef" :index="2" @getSon="quillPurchase" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 商品列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="img" label="商品主图" width="180">
        <template slot-scope="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.img"
            :preview-src-list="[row.img]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="商品价格" />
      <el-table-column prop="stock" label="商品库存" />
      <el-table-column prop="category.name" label="商品分类" />
      <el-table-column prop="status" label="商品上架状态">
        <template slot-scope="{row}">
          <span v-if="row.status===1">上架</span>
          <span v-if="row.status===0">下架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status===0"
            size="small"
            type="primary"
            @click="changeStatus(scope)"
          >上架</el-button>
          <el-button
            v-else
            size="small"
            @click="changeStatus(scope)"
          >下架</el-button>

          <el-button
            type="primary"
            size="small"
            @click="edit(scope.row,'form')"
          >修改</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">

      <el-pagination
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getList, goodsCreate, goodsDelete, findGoods, updateGoods, editGoodStatus } from '@/api/goods.js'
import { getCategoryList } from '@/api/goods/goodsCategory.js'
import uploadImg from '@/components/Common/uploadImg.vue'
import quillEditorVue from '@/components/quillEditorVue.vue'
export default {
  components: { uploadImg, quillEditorVue },
  data() {
    return {
      test: false,
      bindForm: {
        name: null,
        status: null
      },
      tableData: [],
      dialogFormVisible: false,
      form: {
        name: '',
        img: '',
        price: null,
        stock: null,
        status: null,
        category: null,
        sku: [
          {
            skuName: '',
            skuContent: '',
            skuPrice: null,
            skuStock: null
          }
        ],
        details: '',
        mealContont: '',
        purchaseNotes: ''
      },
      editorContent: '',
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 20个字符以内', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],

        stock: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }

        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },
      formLabelWidth: '120px',
      categoryList: [],
      title: '新建商品',
      goodsId: '', // 根据是否有goodsId判断是弹窗新建还是修改
      pageNo: 1,
      pageSize: 5,
      total: 0,
      searchForm: {
        name: null,
        status: null
      }
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    addTest() {
      this.form.test.push({
        user: '',
        psw: ''
      })
    },
    valueInput(e) {
      e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
      this.form.price = e
    },
    onSearch() {
      this.searchForm.name = this.bindForm.name
      this.searchForm.status = this.bindForm.status
      this.getGoodsList()
    },
    reset() {
      this.bindForm = {}
      this.searchForm = {}
      this.getGoodsList()
    },
    // 获取列表
    getGoodsList() {
      getList({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        name: this.searchForm.name,
        status: this.searchForm.status
      }).then((res) => {
        const { code, data } = res
        if (code === 200) {
          console.log('data', data.list)
          this.total = data.pagination.count
          this.tableData = data.list
        }
      })
    },

    // 点击新建按钮
    add(formName) {
      this.dialogFormVisible = true
      this.title = '新建商品'
      this.form.name = ''
      this.form.img = ''
      this.form.sku = [{
        skuName: '',
        skuContent: '',
        skuPrice: null,
        skuStock: null,
        skuId: null
      }]
      this.form.price = null
      this.form.stock = null
      this.form.status = null
      this.form.category = ''
      this.form.details = ''
      this.form.mealContont = ''
      this.form.purchaseNotes = ''

      this.goodsId = ''
      getCategoryList().then((res) => {
        const { data, code } = res
        if (code === 200) {
          console.log('222', data.list)
          this.categoryList = data.list
        }
      })

      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
    },
    // 修改商品按钮
    edit(row, formName) {
      this.dialogFormVisible = true
      this.title = '修改商品'
      getCategoryList().then((res) => {
        const { data, code } = res
        if (code === 200) {
          this.categoryList = data.list
        }
      })
      findGoods(row._id).then(res => {
        const { code, data } = res
        console.log('aaa', data)
        if (code === 200) {
          this.form.name = data.name
          this.form.price = data.price
          this.form.details = data.details
          this.form.img = data.img
          this.form.stock = data.stock
          this.form.status = data.status
          this.form.purchaseNotes = data.purchaseNotes
          this.form.mealContont = data.mealContont
          this.form.category = data.category._id
          if (data.sku.length === 0) {
            this.form.sku = [{
              skuName: '',
              skuContent: '',
              skuPrice: null,
              skuStock: null
            }]
          } else {
            data.sku.forEach(item => {
              item.skuId = item._id
              delete item._id
            })
            console.log('data.sku', data.sku)
            this.form.sku = data.sku
          }

          this.goodsId = data._id
        }
      })
      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
    },
    // 新增规格
    addSku() {
      this.form.sku.push({
        skuName: '',
        skuContent: '',
        skuPrice: null,
        skuStock: null
      })
    },
    // 删除规格
    delSku({ $index }) {
      this.form.sku.splice($index, 1)
    },
    // 富文本子组件传来的值
    quillDetail(e) {
      this.form.details = e
      // console.log(e)
    },
    quillPurchase(e) {
      this.form.purchaseNotes = e
    },
    quillMeal(e) {
      this.form.mealContont = e
    },
    // 新增商品
    createGood() {
      goodsCreate(this.form).then((res) => {
        this.dialogFormVisible = false
        this.getGoodsList()
        this.$message({
          message: '新增成功',
          type: 'success'
        })
      })
    },
    // 修改商品
    updateGood() {
      const { sku, name, img, price, stock, category, details, mealContont, purchaseNotes } = this.form
      console.log('del', sku)
      updateGoods(this.goodsId, {
        sku, name, img, price, stock, category, details, mealContont, purchaseNotes
      }).then(res => {
        const { code } = res
        if (code === 200) {
          this.dialogFormVisible = false
          this.getGoodsList()
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      })
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.goodsId) {
            this.updateGood()
          } else {
            this.createGood()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getListFun()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.getListFun()
      console.log(`当前页: ${val}`)
    },
    handleClick(a) {
      console.log('a', a)
      if (a.status === 1) {
        a.status === 0
      } else {
        a.status === 1
      }
    },
    getCover(url) {
      this.form.img = url
      console.log(url)
    },

    // 删除
    handleDelete({ row }) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsDelete(row._id).then((res) => {
          const { code } = res
          if (code === 200) {
            this.getGoodsList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      })
        .catch(() => {})
    },
    // 修改状态
    changeStatus({ row }) {
      console.log(row)
      const { status, _id } = row
      let _status = 0
      let message = ''
      if (status === 1) {
        _status = 0
        message = '下架成功'
      } else {
        _status = 1
        message = '上架成功'
      }
      editGoodStatus(_id, { status: _status }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message({
            message: message,
            type: 'success'
          })
        }
        this.getGoodsList()
      })
    }
  }
}
</script>

<style lang="scss">
  .el-input__inner{
  line-height: 1px !important;
}

input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

</style>
